/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace Whitemice.ZOGI.Backend
{
  internal class WorkItem
  {
    protected DateTime    enqueueTime;
    protected static int id = 0;
    
    public WorkItem(object payload, RpcPriority priority)
    {
      ID = id++;
      Priority = priority;
      Payload = payload;
      enqueueTime = DateTime.Now;
    }
    
    internal RpcPriority Priority { get; set; }
    internal object Payload { get; set; }
    internal DateTime EnqueueTime { get { return enqueueTime; } }
    internal int ID { get; set; }
  } // end Workitem

  internal class WorkItemComparer : IComparer
  {
    public WorkItemComparer() : base() 
    {
      this.ZLOG("WorkItemComparer created.");
    }

    int IComparer.Compare(object x, object y) 
		{
      if ((x is WorkItem) && (y is WorkItem))
      {
        WorkItem w1 = (x as WorkItem);
        WorkItem w2 = (y as WorkItem);
        if (w1.Priority > w2.Priority) return -1;
        if (w2.Priority > w1.Priority) return 1;
        return (w1.EnqueueTime.CompareTo(w2.EnqueueTime));
      }
      return 0;
    }
  } // end class WorkItemComparer
  
  internal class WorkQueue : ArrayList
  {
    protected static double     BUSY_TIMEOUT_MS = 3000;
    protected static int        POLL_TIMEOUT_MS = 150;
    protected         DateTime?   busyTime;

    public WorkQueue(): base()
    {
      busyTime = null;
    }
    
    public object Dequeue()
    {
      WorkItem w;
      
      lock (base.SyncRoot)
      {
        Hold:
          Monitor.Wait(base.SyncRoot, POLL_TIMEOUT_MS);
        if ((IsBusy) || (base.Count == 0))
          goto Hold;
        this.ZLOG(string.Format("{0} items in work queue", base.Count));
        base.Sort(new WorkItemComparer());
        w = (base[0] as WorkItem);
        base.Remove(w);
        GoBusy();
        if (w.Payload is IZOGICommand) {
          this.ZLOG(string.Format("WorkQueue releasing {0} {1}", 
                                   w.Payload, 
                                  (w.Payload as IZOGICommand).Id));
        } else this.ZLOG(string.Format("WorkQueue releasing {0}", w.Payload));
        return w.Payload;
      }
    } // end Deqeue

    /// <summary>
    /// Queue an object for work at the specified priority 
    /// </summary>
    /// <param name="payload">
    /// A <see cref="System.Object"/>
    /// </param>
    /// <param name="priority">
    /// A <see cref="RpcPriority"/>
    /// </param>
    public void Enqueue(object payload, RpcPriority priority)
    {
      WorkItem w;
      lock (base.SyncRoot)
      {
        w = new WorkItem(payload, priority);
        if (payload is IZOGICommand)
          this.ZLOG(string.Format("Received work item {0} {1} {2}", 
                                  payload,
                                  (payload as IZOGICommand).Id,
                                  w.ID));
        else this.ZLOG(string.Format("Received work item {0} {1}", payload, w.ID));          
        base.Add(w);
        if (payload is CookComputing.XmlRpc.XmlRpcAsyncResult)
          GoFree();
        Monitor.Pulse(base.SyncRoot);
      }
    } // end Enqueue

    /// <summary>
    /// Queue an object for work at the default priority
    /// </summary>
    /// <param name="payload">
    /// A <see cref="System.Object"/>
    /// </param>
    public void Enqueue(object payload)
    {
      this.Enqueue(payload, RpcPriority.Normal);
    } // end Enqueue

    public bool IsBusy
    {
      get 
      {
        if (busyTime == null)
          return false;
        double ms = DateTime.Now.Subtract(busyTime.Value).TotalMilliseconds;
        if (ms > BUSY_TIMEOUT_MS)
        {
          GoFree();
          this.ZLOG("Releasing work queued due to exceeded timeout.");
        } else this.ZLOG(string.Format("Work queue has been busy for {0}ms", ms));
        return true; 
      }
    }

    private void GoBusy()
    {
      busyTime = DateTime.Now;
    }

    private void GoFree()
    {
      busyTime = null;
    }

    public void Complete()
    {
      lock(base.SyncRoot)
      {
        GoFree();
        Monitor.Pulse(base.SyncRoot);
      }
    }
  } // end class WorkQueue
}
